package com.laolang.ssh.service.impl;


import java.lang.reflect.ParameterizedType;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.laolang.ssh.service.BaseService;


@Transactional
@Service("baseService")
@Lazy(true)
@SuppressWarnings("unchecked")
public class BaseServiceImpl<T> implements BaseService<T> {

	@SuppressWarnings("rawtypes")
	public BaseServiceImpl() {
		ParameterizedType type = (ParameterizedType) this.getClass().getGenericSuperclass();
		clazz = (Class) type.getActualTypeArguments()[0];
	}

	@SuppressWarnings("rawtypes")
	private Class clazz;

	@Autowired
	private SessionFactory sessionFactory;

	protected Session getSession() {
		return sessionFactory.getCurrentSession();
	}

	public void save(T t) {
		getSession().save(t);

	}

	public void merge(T t) {
		getSession().merge(t);

	}

	public void delete(Integer id) {
		String hql = "DELETE " + clazz.getSimpleName() + " WHERE id=:id";
		getSession().createQuery(hql).setParameter("id", id).executeUpdate();

	}

	public T findById(Integer id) {
		String hql = "SELECT o FROM " + clazz.getSimpleName() + " o WHERE o.id=:id";
		return (T) getSession().createQuery(hql).setParameter("id", id).uniqueResult();
	}

	public List<T> findAll() {
		String hql = "FROM " + clazz.getSimpleName();
		return getSession().createQuery(hql).list();
	}

	public List<T> findAll(int firstResult, int maxResults) {
		String hql = "FROM " + clazz.getSimpleName();
		firstResult = ( firstResult - 1 ) * maxResults;
		return getSession().createQuery(hql).setFirstResult(firstResult).setMaxResults(maxResults).list();
	}

	public Long findcount() {
		String hql = "SELECT COUNT(o) FROM " + clazz.getSimpleName() + " o";
		return (Long) getSession().createQuery(hql).uniqueResult();
	}

	public Long findpages(Integer size) {
		long count = findcount();
		long pages = count / size;
		if ((count - pages * size) > 0) {
			pages += 1;
		}
		return pages;
	}

}
